<template>
  <div
    v-loading="latLngLoading"
    class="driver-location"
  >
    <div class="location-bar">
      <el-autocomplete
        v-model="form.area"
        size="small"
        :fetch-suggestions="querySearchAsync"
        placeholder="地址"
        @select="handleSelect"
      >
        <el-input
          slot="prepend"
          v-model="form.city"
          size="small"
          placeholder="城市"
        ></el-input>
      </el-autocomplete>
      <el-button
        size="small"
        type="primary"
        @click="search"
      >
        查询
      </el-button>
    </div>
    <div class="operate-bar">
      <div class="driver-refresh" @click="getLatLng">
        <i class="el-icon-location-outline"></i>
      </div>
      <div class="driver-refresh rotate" @click="getLocation">
        <i class="el-icon-refresh"></i>
      </div>
      <div class="driver-refresh" @click="goBack">
        <i class="el-icon-d-arrow-left"></i>
      </div>
    </div>
    <div id="map"></div>
  </div>
</template>

<script>
  /**
   * @Author: lifuzhao
   * @Date: 2019-09-04
   * @Project: driver
   */
  import {mapGetters} from 'vuex'

  export default {
    name: "location"
    , data() {
      return {
        form: {
          city: '铜陵市',
          area: ''
        }
        , latLngLoading: false
        , apiLoading: false
        , lat: ''
        , lng: ''
        , driverList: []
        , markers: []
      }
    }
    , computed: {
      ...mapGetters([
        'isDev'
      ])
    }
    , mounted() {
      this.getLatLng()
    },
    methods: {
      getLatLng() {
        this.latLngLoading = true
        if (!this.mapInstance) {
          // eslint-disable-next-line
          this.mapInstance = new AMap.Map('map', {
            zoom: 12
            , resizeEnable: true
          })
          this.mapInstance.plugin('AMap.Geolocation', () => {
            // eslint-disable-next-line
            this.geolocation = new AMap.Geolocation({
              enableHighAccuracy: true,//是否使用高精度定位，默认:true
              //timeout: 10000,          //超过10秒后停止定位，默认：无穷大
              maximumAge: 0,//100000,      //定位结果缓存0毫秒，默认：0
              convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: false,        //显示定位按钮，默认：true
              // buttonPosition: 'RB',    //定位按钮停靠位置，默认：'LB'，左下角
              // eslint-disable-next-line
              // buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
              showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            })
            this.mapInstance.addControl(this.geolocation)
            this.geolocation.getCurrentPosition()
            // eslint-disable-next-line
            AMap.event.addListener(this.geolocation, 'complete', result => {
              // eslint-disable-next-line
              let {addressComponent, position: {lat, lng}} = result
              let city = this.form.city
              this.lat = lat
              this.lng = lng
              this.form.city = this.isDev ? '铜陵市' : addressComponent.city || city || '铜陵市'
              this.latLngLoading = false
              this.getLocation()
            })
            // eslint-disable-next-line
            AMap.event.addListener(this.geolocation, 'error', (error) => {
              // eslint-disable-next-line
              console.log(error)
              this.lat = ''
              this.lng = ''
              this.latLngLoading = false
            })
          })
          this.mapInstance.plugin('AMap.PlaceSearch', () => {
            // eslint-disable-next-line
            this.placeSearch = new AMap.PlaceSearch({
              pageSize: 50,
              extensions: 'all'
            })
          })
        } else {
          this.geolocation.getCurrentPosition()
        }
      },
      querySearchAsync(str, cb) {
        let city = this.form.city || '铜陵市'
        this.placeSearch.setCity(city)
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.placeSearch.search(str, (status, result) => {
            let list = []
            if (status === 'complete' && result.info === 'OK') {
              let poiList = result.poiList || {}
              list = poiList.pois.map(item => {
                return {
                  value: item.name,
                  address: item.address,
                  lat: item.location.lat,
                  lng: item.location.lng
                }
              })
            }
            cb(list)
          })
        }, 500)
      },
      search() {
        let city = this.form.city || '铜陵市'
        this.placeSearch.setCity(city)
        this.placeSearch.search(this.form.area, (status, result) => {
          let list = []
          if (status === 'complete' && result.info === 'OK') {
            let poiList = result.poiList || {}
            list = poiList.pois.map(item => {
              return {
                value: item.name,
                address: item.address,
                lat: item.location.lat,
                lng: item.location.lng
              }
            })
          }
          if (list.length === 0) {
            this.$message('无结果')
          } else {
            this.form.lat = list[0].lat
            this.form.lng = list[0].lng
            this.getLocation()
          }
        })
      },
      handleSelect(item) {
        this.lat = item.lat
        this.lng = item.lng
        this.getLocation()
      },
      goBack() {
        this.$router.back()
      },
      getLocation() {
        this.apiLoading = true
        this.$axios.get('/api/v1/drivers/nearby', {
          params: {
            lat: this.lat
            , lng: this.lng
          }
        })
          .then(async data => {
            let list = []
            if (Array.isArray(data)) {
              let promises = []
              console.log(data)
              for (let i = 0; i < data.length; i = i + 40) {
                let start = i,
                  end = start + 40
                let convert = []
                data.slice(start, end).forEach(item => {
                  let position = item.location || {},
                    {lat, lng} = position
                  if (lat && lng) {
                    convert.push([lng, lat])
                  }
                })
                if (convert.length !== 0) {
                  promises.push(new Promise((resolve, reject) => {
                    // eslint-disable-next-line
                    AMap.convertFrom(convert, 'baidu', (status, result) => {
                      if (result.info === 'ok') {
                        resolve(result.locations)
                      } else {
                        reject()
                      }
                    })
                  }))
                }
              }
              await Promise.all(promises)
                .then(results => {
                  results.forEach((result, i) => {
                    result.forEach((resultItem, i2) => {
                      let index = (i - 1) * 40 + i2
                      data[index].location = result[i2]
                    })
                  })
                })
                .catch(() => {
                  list = []
                })
              list = data
            }
            this.driverList = list
            this.renderMap()
          })
          .catch(() => {
          })
          .finally(() => {
            this.apiLoading = false
          })
      }
      , renderMap() {
        // eslint-disable-next-line
        let center = new AMap.LngLat(this.lng, this.lat)
        this.mapInstance.setCenter(center)
        this.markers.forEach(m => {
          this.mapInstance.remove(m)
        })
        this.markers = []
        this.driverList.forEach(({location, username, state}) => {
          // eslint-disable-next-line
          let poi = new AMap.LngLat(location.lng, location.lat)
          // eslint-disable-next-line
          let icon = new AMap.Icon({
            // eslint-disable-next-line
            size: new AMap.Size(36, 36),
            // eslint-disable-next-line
            imageSize: new AMap.Size(24, 24),
            image: state === 1 ? '/blue.png' : '/red.png'
          })
          // eslint-disable-next-line
          let marker = new AMap.Marker({
            icon: icon,
            position: poi,
            label: {
              content: `<div class="amap-marker-label-content">${username}</div>`
            }
          })
          this.markers.push(marker)
          marker.on('mouseover', (event) => {

          })
          this.mapInstance.add(marker)
        })
      }
    }
  }

</script>

<style lang="less">
  .driver-location {
    width: 100%;
    height: 100%;
    position: relative;

    .location-bar {
      position: absolute;
      z-index: 100;
      left: 20px;
      top: 20px;
      box-shadow: 1px 2px 1px rgba(0, 0, 0, .15);
      display: flex;
      align-items: center;

      .el-input-group__prepend {
        padding: 0;
        border: none;

        .el-input__inner {
          padding: 0 10px;
          border-width: 0 1px 0 0;
          border-style: solid;
          border-right-color: #eee;
          width: 80px;

        }
      }

      .el-input__inner {
        box-sizing: border-box;
        border: 0;
        padding: 9px 0;
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
        line-height: 20px;
        font-size: 16px;
        height: 38px;
        color: #333;
        position: relative;
        border-radius: 2px 0 0 2px;
        width: 320px;
      }

      .el-button {
        width: 57px;
        height: 38px;
        float: left;
        border: 0;
        padding: 0;
        cursor: pointer;
        border-radius: 0 2px 2px 0;
        box-shadow: 1px 2px 1px rgba(0, 0, 0, .15);
        background-color: #3385ff;
      }
    }

    .operate-bar {
      position: absolute;
      right: 10px;
      bottom: 20px;
      z-index: 100;
      display: flex;
      flex-direction: column-reverse;

      .driver-refresh {
        width: 37px;
        height: 37px;
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 3px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;

        & + .driver-refresh {
          margin-bottom: 5px;
        }

        &.rotate:hover {
          i {
            transform: rotate(180deg);
          }
        }

        i {
          transition: all 0.3s;
          color: #6e6e6e;
          font-weight: bolder;
        }
      }
    }

    #map {
      position: relative;
      z-index: 10;
      width: 100%;
      height: 100%;
      min-height: 400px;
      background-color: #eee;

      .amap-marker-label {
        top: -38px !important;
        border: none;
        background: transparent;
        width: 24px;
        overflow: visible;
        display: flex;
        justify-content: center;

        .amap-marker-label-content {
          display: inline-flex;
          background: #fff;
          color: #606266;
          font-size: 14px;
          padding: 8px 12px;
          box-sizing: border-box;
          border: 1px solid #ebeef5;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
        }
      }
    }
  }
</style>
